<?php

namespace app\siteadmin\service;

use app\siteadmin\model\User;
use app\siteadmin\model\Order;
use app\Response;
use think\facade\Config;
use think\facade\Log;
use Vtiful\Kernel\Excel;

class OrderService
{

    /***
     * 订单列表
    */
    public static function orderListSerivce($a_uid,$page,$num,$post_num,$m_phone,$state,$start_time,$end_time){
        $adminInfo = User::info(["uid"=>$a_uid]);
        if($adminInfo["paid"] == 0&&$adminInfo["type"] == 10){
            $paid = $adminInfo["uid"];
        }else{
            $paid = $adminInfo["paid"];
        }
        $where[] = ["paid","=",$paid];
        if(!empty($post_num)){
            if(ctype_digit($post_num)){
                if(!empty($post_num)){
                    $where[] = ["o_number","=",$post_num];
                }
            }else{
                preg_match_all('/\d+/', $post_num, $numbers); // 匹配数字
                preg_match_all('/[A-Za-z]+/', $post_num, $letters); // 匹配字母
                if(!empty($numbers)){
                    $o_number = $numbers[0][0];
                    $where[] = ["o_number","=",$o_number];
                }
                if(!empty($letters)){
                    $letters = $letters[0][0];
                    $where[] = ["prefix","like","%".$letters."%"];
                }
            }
        }
        if(!empty($m_phone)){
            $m_where[] = ["phone","like","%".$m_phone."%"];
            $m_info = User::info($m_where);
            if(!empty($m_info)){
                $where[] = ["uid","=",$m_info['id']];
            }else{
                $where[] = ["uid","=",0];
            }
        }
        if(!empty($state)){
            $where[] = ["state","=",$state];
        }
        if(!empty($start_time)){
            $startTime = strtotime($start_time);
            $where[] = ["addtime",">=",$startTime];
        }
        if (!empty($end_time)){
            $endTime = strtotime($end_time)+86400;
            $where[] = ["addtime","<=",$endTime];
        }

        $order_list = Order::dataList($where,$page,$num);
        if (!empty($order_list)){
            $data = $order_list->toArray();
            foreach($data as $k=>$v){
                $data[$k]["retime"] = !empty($v["retime"])?date("Y-m-d H:i:s",$v["retime"]):"";
                $data[$k]["addtime"] = !empty($v["addtime"])?date("Y-m-d H:i:s",$v["addtime"]):"";
                $data[$k]["address_info"] = !empty($v["address_info"])?(array)json_decode($v["address_info"]):"";
            }
            $count = Order::dataCount($where);
        }else{
            $data = [];
            $count = 0;
        }
        return Response::wrapData($data,$count);
    }

    /****
     * 订单详情
    */
    public static function orderDetailedService($oId){
        $orderInfo = Order::dataView(["id"=>$oId]);
        if(!empty($orderInfo)){
            $info = $orderInfo;
            $info = !empty($info["retime"])?date("Y-m-d H:i:s",$info["retime"]):"";
            $info = !empty($info["addtime"])?date("Y-m-d H:i:s",$info["addtime"]):"";
            return Response::wrapData($info);
        }else{
            return Response::wrapData($data = []);
        }
    }

    /***
     * 订单修改
    */
    public static function orderEditService($oId,$state){
        //   状态 1已录入 2已到网点  4已送达 6已结算
        $oInfo = Order::dataView(["id"=>$oId]);
        if(!$oInfo){
            return Response::wrapError(0,"未查询到当前订单!");
        }
        switch ($state){
            case 6:
                $data = ["state"=>6,"overtime"=>time()];
                break;
            default:
                $data = ["state"=>$state];
                break;
        }
        $res = Order::dataEdit(["id"=>$oId],$data);
        if ($res){
            return Response::wrapData();
        }else{
            return Response::wrapError(0,"修改失败!");
        }
    }

    /****
     * 订单批量操作
    */
    public static function orderBatchEditService($a_uid,$oIds,$state){
        if(empty($oIds)){
            return Response::wrapError(0,"参数异常!");
        }
        if(is_array($oIds)){
            $oIds = implode(",",$oIds);
        }
        switch ($state){
            case 6:
                $data = ["state"=>6,"overtime"=>time()];
                break;
            default:
                $data = ["state"=>$state];
                break;
        }
        $where[] = ["id","in",$oIds];
        $res = Order::dataEdit($where,$data);
        if ($res){
            Log::record('管理员ID:'.$a_uid.' 批量操作订单'.json_encode($oIds,JSON_UNESCAPED_UNICODE));
            return Response::wrapData();
        }else{
            return Response::wrapError(0,"修改失败!");
        }
    }

    public static function orderExcelExportService($m_phone,$state,$start_time,$end_time,$a_uid){
        $adminInfo = User::info(["uid"=>$a_uid]);
        if(!$adminInfo){
            return Response::wrapError(-200,"登录信息异常!");
        }
        if($adminInfo["type"] != 10){
            $paid = $adminInfo["paid"];
            $storeName = User::info(["uid"=>$paid])["nickname"];
        }else{
            $paid = $adminInfo["uid"];
            $storeName = $adminInfo["nickname"];
        }
        $where[] = ["o.paid","=",$paid];
        if(is_numeric($state)){
            $where[] = ["o.state","=",$state];
        }
        if (!empty($m_phone)){
            $mInfo = User::info(["phone"=>$m_phone]);
            if(!$mInfo){
                $where[] = ["o.uid","=",$mInfo["uid"]];
            }
        }
        if(!empty($start_time)){
            $startTime = strtotime($start_time);
            $where[] = ["o.addtime",">=",$startTime];
        }
        if (!empty($end_time)){
            $endTime = strtotime($end_time)+86400;
            $where[] = ["o.addtime","<=",$endTime];
        }
        $data = Order::dataListJoinAll($where,$field="o.id,o.prefix,o.o_number,o.addtime,o.state,o.overtime,u.phone");

        if($data){
            $list = $data;
            $info = [];
            foreach($list as $k=>$v){
                $info[$k]["post_num"] = !empty($v["prefix"])?$v["prefix"].$v["o_number"]:$v["o_number"];
                $info[$k]["m_phone"] = !empty($v["phone"])?$v["phone"]:0;
                switch ($v["state"]){
                    case 1:
                        $info[$k]["state_str"] = "已录入";
                        break;
                    case 2:
                        $info[$k]["state_str"] = "已到网点";
                        break;
                    case 4:
                        $info[$k]["state_str"] = "已送达";
                        break;
                    case 6:
                        $info[$k]["state_str"] = "已结算";
                        break;
                }
                $info[$k]["storeName"] = $storeName;
                $info[$k]["addtime"] = !empty($v["addtime"])?date("Y-m-d H:i:s",$v["addtime"]):"";
                $info[$k]["overtime"] = !empty($v["overtime"])?date("Y-m-d H:i:s",$v["overtime"]):"";
            }
        }else{
            return Response::wrapError(0,  "暂无数据！");
        }
        $config = [
            'path' =>Config::get('mapping.xslwriter_path').'uploads/xlsx' // xlsx文件保存路径
        ];
        $excel  = new Excel($config);
        $excelName = "订单列表".time();
        $filePath = $excel->fileName($excelName.'.xlsx', 'sheet1')
            ->header(["快递单号","商家手机号","订单状态","网点名称","录入时间","结算时间"])
            ->data($list)
            ->output();
        if ($filePath){
            return Response::wrapData(["path"=>'uploads/xlsx/'.$excelName.'.xlsx']);
        }else{
            return Response::wrapError(0,"导出失败!");
        }

    }
}